#!/usr/bin/env python

# Author: Edward Roualdes
#         [2012.11.20]
#         University of Kentucky

from ConfigParser import SafeConfigParser
import multiprocessing
import os.path
import sys

# sanity checks are those helpful little comments that a program outputs
# to remind you of the options specified


def sane(CONFIGFILE):
    """perform sanity checks for NextAllele and output user specified options.
    """

    # parse CONFIGFILE
    parser = SafeConfigParser(dict_type = dict)
    parser.read(CONFIGFILE)

    # store [OPTIONS] in map
    ls = ['REFERENCEFILE', 'BARCODEFILE', 'INPUTFILE', \
          'OUTPUTDIRECTORY', 'BLASTREPORT']
    opts = {}                   # the map of options

    if 'OPTIONS' in parser.sections():
        for i in ls:
            opts[i] = os.path.normpath(parser.get('OPTIONS', i))
    else:
        print ("CONFIGFILE needs an [OPTIONS] section;"
               " see README file for an example.")
        sys.exit()

    # split ALIGNTOOL into list = [aligner, path]
    opts['ALIGNTOOL'] = parser.get('OPTIONS', 'ALIGNTOOL').split(', ')
    opts['ALIGNTOOL'][1] = os.path.normpath(opts['ALIGNTOOL'][1])
    opts['DO'] = parser.get('OPTIONS', 'DO').split(', ')
    opts['DO'] = [x.lower() for x in opts['DO']]

    # add [EXTRAS] to map if they exist
    if 'EXTRAS' in parser.sections():
        if parser.items('EXTRAS'):

            for name, value in parser.items('EXTRAS'):
                opts[name] = value

            if opts['cpu'] == '': # use cpu_count by default
                opts['cpu'] = multiprocessing.cpu_count()

            # use 'modified' by defualt for edited PAs'
            if opts['edit_pa'] == '':
                opts['edit_pa'] = 'modified'
    else:                       # choose sensible defaults
        opts['cpu'] = multiprocessing.cpu_count()
        opts['edit_pa'] = 'modified'

    # do appropriate files exist?
    for i in ls:
        if i != 'OUTPUTDIRECTORY':
            if not os.path.exists(opts[i]):
                print i, 'does not exist.'
                sys.exit()
    if not os.path.exists(opts["ALIGNTOOL"][1]): 
        print "ALIGNTOOL path does not exist."
        sys.exit()

    # should sorting be performed
    opts['sort'] = True if 'sort' in opts['DO'] else False

    # should trimming be performed
    opts['trim'] = False if 'notrim' or not opts['sort'] else True

    # should aligning be performed
    opts['align'] = True if 'align' in opts['DO'] else False
        
    # should haplotype calling be performed
    opts['phase'] = True if 'phase' in opts['DO'] else False

    # should STRUCTURE file be created
    opts['structure'] = True if 'structure' in opts['DO'] else False

    # should haplotype estimating be performed
    opts['unphase'] = True if 'unphase' in opts['DO'] else False

    # print options so that users are reminded of their input
    print "\nUser specified options:\n"
    for i in ls:
        print i, '=', opts[i]
    print 'ALIGNTOOL =', opts['ALIGNTOOL'][1]
    print 'sort =', opts['sort']
    print 'align =', opts['align']
    print 'phase =', opts['phase']
    print 'unphase =', opts['unphase']
    print "\n"
    return opts


if __name__ == '__main__':

    import sys
    import pprint

    pp = pprint.PrettyPrinter(indent=4)
    
    c = sys.argv[1]             # CONFIGILE
    pp.pprint(sane(c))
